package ans.p216;

import test.Entrance;

import java.util.LinkedList;
import java.util.List;

/**
 * #      216
 * 名称   组合总和 III
 * 链接   https://leetcode-cn.com/problems/combination-sum-iii
 * 题解   [791](https://leetcode-cn.com/problems/combination-sum-iii/solution)
 * 通过率 73.9%
 * 难道   中等
 */

public class Solution {
    @Entrance
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new LinkedList<>();
        traceback(ans, new LinkedList<>(), 0, k, n);
        return ans;
    }

    private void traceback(List<List<Integer>> ans, List<Integer> temp, int index, int k, int n) {
        if (temp.size() == k) {
            if (n == 0) {
                ans.add(new LinkedList<>(temp));
            }
            return;
        }
        for (int i = index + 1; i <= 9; i++) {
            temp.add(i);
            traceback(ans, temp, i, k, n - i);
            temp.remove(temp.size() - 1);
        }
    }
}